package pub.cleangao.common.unique;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IDWorker {


    private static Snowflake snowflake = null;

    static {
        init();
    }

    private static void init() {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            String currentIp = inetAddress.getHostAddress();
            String localhostName = inetAddress.getHostName();
            snowflake = new Snowflake(Math.abs(Ip2Integer.ipToInt(currentIp)) % 31, Math.abs(Scale62Convertor.scale62To10(MD5.sum(localhostName))) % 31L);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }


    public static long nextId() {
        if (snowflake == null) {
            init();
        }
        return snowflake.nextId();
    }

    public static String nextIdChar() {
        if (snowflake == null) {
            init();
        }
        return Scale62Convertor.scale10To62(snowflake.nextId());
    }

    public static String nextIdChar(int length) {
        if (snowflake == null) {
            init();
        }
        StringBuilder rst = new StringBuilder(Scale62Convertor.scale10To62(snowflake.nextId()));
        while (rst.length() < length) {
            rst.insert(0, "0");
        }
        return rst.toString();
    }


}
